package com.shire.movienizerdroid.view.adapter;

import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.shire.movienizerdroid.R;
import com.shire.movienizerdroid.thirdparty.DownloadImageTask;
import com.shire.movienizerdroid.utils.Utils;

/**
 * @author yhernandezdiaz
 */
public class MovieListAdapter extends CursorAdapter {
	private final LayoutInflater mInflater;

	public MovieListAdapter(Context context, Cursor c) {
		super(context, c, false);
		mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	@Override
	public View newView(Context context, Cursor cursor, ViewGroup parent) {
		final View view = mInflater.inflate(R.layout.movielistitem, parent, false);
		view.setTag(new ViewHolder(view.findViewById(R.id.mliImage), view.findViewById(R.id.mliTitle), view.findViewById(R.id.mliDescription), view.findViewById(R.id.mliYear)));
		return view;
	}

	@Override
	public void bindView(View view, Context context, Cursor cursor) {
		final ViewHolder vh = (ViewHolder) view.getTag();

		vh.title.setText(cursor.getString(1));
		vh.description.setText(cursor.getString(2));
		vh.year.setText(cursor.getString(3));

		if (null != vh.coverImage.getTag()) {
			((AsyncTask<?, ?, ?>) vh.coverImage.getTag()).cancel(true);
			vh.coverImage.setTag(null);
		}

		vh.coverImage.setImageBitmap(null);
		vh.coverImage.setTag((new DownloadImageTask()).execute(new Object[] { vh.coverImage, Utils.getCoverThumbnailInfo(context, cursor.getString(4), null) }));
	}

	private static final class ViewHolder {
		final ImageView coverImage;
		final TextView title;
		final TextView description;
		final TextView year;

		public ViewHolder(View coverImage, View title, View description, View year) {
			super();
			this.coverImage = (ImageView) coverImage;
			this.title = (TextView) title;
			this.description = (TextView) description;
			this.year = (TextView) year;
		}
	}

}
